<template>
    <div class="app-container customer-div">
        <div style="margin-top: 40px">
            <!--搜索-->
            <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
                <el-form-item label="关键字：">
                    <el-input v-model="listQuery.keywords"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button
                            @click="handleSearchList()"
                            type="primary">
                        查询
                    </el-button>
                    <el-button
                            @click="showDialog('add')"
                            type="primary">
                        新增
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--数据列表-->
        <div class="table-container">
            <el-table
                    v-loading="listLoading"
                    :data="tableData"
                    border
                    style="width: 100%; margin-top: 20px">
                <el-table-column  label="商品名称"  align="center" prop="orderSn">
                    <template slot-scope="scope">
                        <div>
                            {{scope.row.goodsSn}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                        align="center"
                        label="类型">
                    <template slot-scope="scope">
                        {{scope.row.limitType == 'everyday' ? '固定' : '自定义'}}
                    </template>
                </el-table-column>
                <el-table-column
                        align="center"
                        label="限额">
                    <template slot-scope="scope">
                        {{scope.row.limitNum}}
                    </template>
                </el-table-column>
                <el-table-column
                        align="center"
                        label="时间">
                    <template slot-scope="scope">
                        {{scope.row.limitType == 'everyday' ? '每天' : scope.row.limitDay}}
                    </template>
                </el-table-column>

                <el-table-column
                        fixed="right"
                        label="操作"
                        align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                size="mini"
                                @click="showDialog3(scope.row)">编辑
                        </el-button>
                        <el-button
                                type="text"
                                size="mini"
                                @click="delRow(scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    layout="total, sizes,prev, pager, next,jumper"
                    :current-page.sync="listQuery.pageNum"
                    :page-size="listQuery.pageSize"
                    :page-sizes="[10,15,20]"
                    :total="count">
            </el-pagination>
        </div>

        <!--增加限额-->
        <el-dialog
                :close-on-click-modal="false"
                :beforeClose="handleClose"
                title="限额信息"
                :visible.sync="dialogVisible"
                width="500px">
            <el-form :model="priceForm" size="mini" label-width="100x"  ref="priceForm" :rules="rules">
                <el-form-item label="牌号：" prop="kingId"  v-if="type=='add'">
                    <el-select
                            clearable
                            v-model="priceForm.kingId"
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入关键词"
                            :remote-method="remoteMethod"
                            :loading="loading">
                        <el-option
                                v-for="item in options"
                                :key="item.kingId"
                                :label="item.goodsSn"
                                :value="item.kingId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="牌号：" v-if="type=='edit'">
                    <span>{{priceForm.goodsSn}}</span>
                </el-form-item>
                <el-form-item label="时间："  prop="limitType">
                    <el-radio-group v-model="priceForm.limitType">
                        <el-radio label="everyday">每天</el-radio>
                        <el-radio label="date">自定义时间</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="限额数量：" prop="limitNum" v-if="priceForm.limitType=='everyday'">
                    <el-input v-model="priceForm.limitNum" style="width:195px"></el-input>
                </el-form-item>
                <el-form-item label="自定义设置：" v-if="priceForm.limitType=='date'">
                    <el-button size="small" type="text" @click="showDialog2">添加时间</el-button>
                    <el-table ref="advertisementTable"
                              :data="priceForm.list"
                              style="width: 100%;margin-top:20px"
                              v-loading="listLoading" border>
                        <el-table-column label="日期"  align="center">
                            <template slot-scope="scope">{{scope.row.limitDate }}</template>
                        </el-table-column>
                        <el-table-column label="限额数量"  align="center">
                            <template slot-scope="scope">{{scope.row.limitNum }}</template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button
                                        size="mini"
                                        type="text"
                                        @click="delRow2(scope.$index)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                  <el-button @click="handleClose">取 消</el-button>
                  <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
            </span>
        </el-dialog>

        <!--编辑限额-->
        <el-dialog
                :close-on-click-modal="false"
                :beforeClose="handleClose3"
                title="限额信息"
                :visible.sync="dialogVisible3"
                width="500px">
            <el-form :model="editForm" size="mini" label-width="100x"  ref="editForm" :rules="rules3">
                <el-form-item label="牌号：">
                    <span>{{editForm.goodsSn}}</span>
                </el-form-item>
                <el-form-item label="时间：" >
                    <span> {{editForm.limitType == 'everyday' ? '每天' : editForm.limitDay}}</span>
                </el-form-item>
                <el-form-item label="限额数量：" prop="limitNum">
                    <el-input v-model="editForm.limitNum" style="width:195px"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                  <el-button @click="handleClose3">取 消</el-button>
                  <el-button type="primary" @click="handleConfirm3">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
                title="增加时间"
                :visible.sync="dialogVisible2"
                width="400px">
            <el-form label-width="100px" size="small" ref="dateForm" :rules="rules2" :model="dateForm">
                <el-form-item label="日期：" prop="date">
                    <el-date-picker
                            value-format="yyyy-MM-dd"
                            v-model="dateForm.date"
                            type="date"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="限额数量：" prop="limitNum">
                    <el-input v-model="dateForm.limitNum" style="width:195px"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="onSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    import {goodsLimitList,addGoodsLimit,editGoodsLimit,goodsList,delGoodsLimit} from '@/api/company'
    import {getAddressList,} from '@/api/partner'
    import {validateCommission} from '@/utils/validate';
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    const defaultListQuery={
        pageNum: 1,
        pageSize: 10,
        keywords: '',
    };
    const defaultPriceForm={
        kingId : null,
        limitNum   : "",
        goodsSn:'',
        limitType:'',
        list:[]
    };
    const defaultEditForm = {
        limitNum : "",
        goodsSn:'',
        limitType:'',
        limitDay:'',
        dplId:'',

    };
    const defaultDataForm = {
        date:''
    };
    export default {
        name: "index",
        data(){
            const isvalidateCommission = (rule, value, callback) => {
                if (!validateCommission(parseFloat(value))) {
                    callback(new Error('非负整数或小数'))
                } else if(value > 99999999){
                    callback(new Error('最大值为99999999'))
                }else {
                    callback()
                }
            };
            return {
                listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
                tableData: [],
                count: 0,
                listLoading: false,
                userOptionList:[],
                roles:store.getters.roles ? store.getters.roles : [],
                dialogVisible:false,
                priceForm:JSON.parse(JSON.stringify(defaultPriceForm)),
                rules:{
                    kingId : [{required: true, message: '请选择商品', trigger: 'change'},],
                    limitType:[{required: true, message: '请选择时间类型', trigger: 'change'},],
                    limitNum   : [{required: true, trigger: 'blur',validator: isvalidateCommission}],
                },
                btnLoading : false,
                type:'',
                loading:false,
                options:[],
                rules2: {
                    date:[{ required: true, message: '请输入日期', trigger: 'change' }],
                    limitNum   : [{required: true, trigger: 'blur',validator: isvalidateCommission}],
                },
                dialogVisible2:false,
                list:[],
                dateForm: JSON.parse(JSON.stringify(defaultDataForm)),
                dialogVisible3:false,
                editForm:JSON.parse(JSON.stringify(defaultEditForm)),
                rules3:{
                    limitNum   : [{required: true, trigger: 'blur',validator: isvalidateCommission}],
                }
            }
        },
        created() {
            this.getList();
        },
        methods:{
            showDialog3(item){
                this.editForm.goodsSn = item.goodsSn;
                this.editForm.limitNum = item.limitNum;
                this.editForm.limitType = item.limitType;
                this.editForm.limitDay = item.limitDay;
                this.editForm.dplId = item.dplId;
                this.dialogVisible3 = true;
            },
            handleClose3(){
                this.dialogVisible3 = false;
                this.$refs['editForm'].clearValidate();
            },
            handleConfirm3(){
                this.$refs['editForm'].validate((valid) => {
                    if (valid) {
                        let pa = {};
                        pa.dplId = this.editForm.dplId;
                        pa.limitNum = this.editForm.limitNum;
                        editGoodsLimit(pa).then(()=>{
                            this.dialogVisible3 = false;
                            this.getList()
                        }).catch(()=>{
                        })
                    }
                })
            },
            delRow2(index){
                this.$confirm('是否确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.priceForm.list.splice(index,1)
                }).catch(() => {

                });
            },
            showDialog2(){
                this.dialogVisible2 = true;
                this.dateForm =  JSON.parse(JSON.stringify(defaultDataForm));
            },
            closeDialog(){
                this.dialogVisible2 = false;
                this.$refs['dateForm'].clearValidate();
            },
            onSubmit(){
                this.$refs['dateForm'].validate((valid) => {
                    if (valid) {
                        this.priceForm.list.push({limitDate:this.dateForm.date,limitNum:this.dateForm.limitNum});
                        this.dialogVisible2 = false;
                    }
                });
            },


            remoteMethod(query) {
                if (query !== '') {
                    this.loading = true;
                    this.loading = false;
                    goodsList({keywords:query}).then((res)=>{
                        this.options = res.list;
                    })
                } else {
                    this.options = [];
                }
            },

            //删除
            delRow(item){
                this.$confirm('确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delGoodsLimit({dplId:item.dplId}).then(()=>{
                        this.getList();
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //显示增加限额弹窗
            showDialog(type,item){
                this.dialogVisible = true;
                this.priceForm = JSON.parse(JSON.stringify(defaultPriceForm));
                this.type = type;
                if(type == 'edit'){

                }
            },

            //关闭增加限额弹窗
            handleClose(){
                this.dialogVisible = false;
                this.$refs.priceForm.clearValidate();
            },

            //提交增加限额
            handleConfirm(){
                this.$refs['priceForm'].validate((valid) => {
                    if (valid) {
                        this.btnLoading = true;
                        let fn = this.type == 'add' ? addGoodsLimit : editGoodsLimit;
                        let pa = {};
                        pa.kingId = this.priceForm.kingId;
                        pa.limitType = this.priceForm.limitType;
                        pa.list = this.priceForm.list;
                            if(pa.limitType == 'everyday'){
                            pa.list = [{limitDate:'',limitNum:this.priceForm.limitNum}]
                        }
                        fn(pa).then(()=>{
                            this.btnLoading = false;
                            this.dialogVisible = false;
                            this.getList()
                        }).catch(()=>{
                            this.btnLoading = false;
                        })
                    }
                })
            },

            handleSizeChange(val){
                this.listQuery.pageNum = 1;
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val){
                this.listQuery.pageNum = val;
                this.getList();
            },

            handleSearchList(){
                this.listQuery.pageNum = 1;
                this.getList();
            },

            //获取列表
            getList() {
                this.listLoading = true;
                goodsLimitList(this.listQuery).then(response => {
                    this.tableData = response.list;
                    this.count = response.count;
                    this.statisticsAmount = response.statisticsAmount;
                    this.statisticsCount = response.statisticsCount;
                    this.statisticsGoodsNum = response.statisticsGoodsNum;
                    this.listLoading = false;
                }).catch(()=>{
                    this.listLoading = false;
                });
            },

            //去收款单页
            toReceiptList(item){
                localStorage.setItem('accountingListQuery', JSON.stringify(this.listQuery));
                this.$router.push({name:'receiptList',query:{orderSn:item.orderSn}})
            },
        },
    }
</script>

<style scoped lang="scss">
    .upload-div{
        text-align: center;
        position:relative;
        #upload{

            opacity: 0;
            position: absolute;
            z-index: 1;
            width:154px;
            height:40px
        }
    }
</style>
